package pl.edu.mimuw.mas.agent.behaviour.helicopter.verification;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.UngroundedException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

import java.io.IOException;

import pl.edu.mimuw.mas.agent.HelicopterAgent;
import pl.edu.mimuw.mas.agent.behaviour.ServerBehaviour;
import pl.edu.mimuw.mas.message.PositionMessage;
import pl.edu.mimuw.mas.message.VerifyOfferMessage;
import pl.edu.mimuw.mas.util.Position;
import pl.edu.mimuw.mas.util.PositionHelper;

/**
 * Zachowanie odpowiadające ofertą lub odmową na CFP w sprawie weryfikacji
 * łosia.
 */
public class SendOfferServerBehaviour extends ServerBehaviour {
	private static final long serialVersionUID = -983200944357142195L;

	public SendOfferServerBehaviour(HelicopterAgent agent) {
		super(agent);
		
		MessageTemplate mt = MessageTemplate.and(
				MessageTemplate.MatchConversationId(HelicopterAgent.HELICOPTER_VERIFY_CONV),
				MessageTemplate.MatchPerformative(ACLMessage.CFP)
		);
		setMessageTemplate(mt);
	}

	public boolean doAction(ACLMessage msg, ACLMessage reply) throws UngroundedException, CodecException, OntologyException, UnreadableException, IOException {
		HelicopterAgent ha = (HelicopterAgent) myAgent;
		
		PositionMessage pmg = (PositionMessage) msg.getContentObject();
		Position pos = ha.getPosition();
		
		if(ha.doPreVerify()) {
			reply.setPerformative(ACLMessage.PROPOSE);
			reply.setContentObject(new VerifyOfferMessage(ha.getAID(), PositionHelper.getDistance(pos.x, pos.y, pmg.x, pmg.y)));
			
			ha.addBehaviour(new ListenOfferAcceptanceBehaviour(ha, msg.getSender()));
			
		} else {
			reply.setPerformative(ACLMessage.REFUSE);
		}
		
		return true;
	}
}
